<template>
  <div class="login-container">
    <div class="login-box">
      <!-- <div class="login-box-l">
        <div class="mask" />
        <img class="logo" src="../../assets/login/logo_white.png" alt="">
        <div class="title">后台管理</div>
        <div class="sub">用互联网科技赋能传统珠宝商</div>
      </div> -->

      <div class="login-box-r">
        <div class="header">
          <div
            class="header-item"
            :class="loginType === 'account' && 'active'"
            @click="changeLoginType('account')"
          >账号登录</div>
        </div>

        <el-form v-if="loginType === 'account'" key="loginForm" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" label-position="left">
          <el-form-item prop="username" style="margin-bottom: 32px;">
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="请输入手机号"
              name="username"
              type="text"
              maxlength="11"
              autocomplete="on"
            >
              <template slot="prepend">手机</template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password" style="margin-bottom: 40px;">
            <el-input
              ref="password"
              v-model="loginForm.password"
              type="password"
              placeholder="请输入登录密码"
              name="password"
              auto-complete="new-password"
              @keyup.enter.native="handleLogin"
            >
              <template slot="prepend">密码</template>
            </el-input>
          </el-form-item>

          <el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">立即登录</el-button>
        </el-form>

        <el-form v-else key="captchaForm" ref="loginForm" :model="captchaForm" :rules="captchaRules" class="login-form" label-position="left">
          <el-form-item prop="phone" style="margin-bottom: 32px;">
            <el-input
              ref="phone"
              v-model="captchaForm.phone"
              placeholder="请输入手机号"
              name="phone"
              type="text"
              maxlength="11"
            >
              <template slot="prepend">手机</template>
            </el-input>
          </el-form-item>

          <el-form-item prop="captcha" style="margin-bottom: 40px;">
            <el-input
              ref="captcha"
              v-model="captchaForm.captcha"
              type="text"
              placeholder="请输入验证码"
              name="captcha"
              @keyup.enter.native="handleLogin"
            >
              <template slot="prepend">验证码</template>
            </el-input>
            <el-button type="text" :disabled="time !== null" class="verify-text" @click="handleSendCaptcha">
              <div class="line" />
              <span class="text" v-text="timeText" />
            </el-button>
          </el-form-item>

          <el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">立即登录</el-button>
        </el-form>

        <!-- <div class="footer">
          登录即同意
          <a href="https://pys.pysfeicui.com/term_20201225.html" target="_blank"></a>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script>
// import { validUsername } from '@/utils/validate'
import QRCode from 'qrcodejs2'
import { captcha, notice } from '@/api/common'
import { setToken } from '@/utils/auth'
import { Message } from 'element-ui'

export default {
  name: 'Login',
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('手机号码不能为空'))
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error('手机号码格式不正确'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入登陆密码'))
      } else {
        callback()
      }
    }
    const validateCaptcha = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    return {
      loginType: 'account',
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validatePhone }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      captchaForm: {
        phone: '',
        captcha: ''
      },
      captchaRules: {
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        captcha: [{ required: true, trigger: 'blur', validator: validateCaptcha }]
      },
      qrRes: '',
      qrTimer: null,
      isFail: false,
      loading: false,
      redirect: undefined,
      time: null,
      timeInterval: null
    }
  },
  computed: {
    timeText: function() {
      if (this.time) {
        return '已发送 ' + this.time + 's'
      } else if (this.time === 0) {
        return '请稍后'
      } else {
        return '发送验证码'
      }
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    if (this.loginType === 'qrCode') {
      this.bindQrCode()
    }
  },
  methods: {
    changeLoginType(type) {
      this.loginForm.username = ''
      this.loginForm.password = ''
      if (type === 'qrCode') {
        this.loginType = 'qrCode'
        this.$nextTick(() => {
          this.handleRefresh()
        })
      } else {
        this.clearQrTimer()
        this.loginType = type
      }
    },
    async bindQrCode() {
      const qrCode = document.querySelector('.qr')
      if (qrCode) {
        qrCode.innerHTML = '<i class="el-icon-loading" style="font-size: 40px;"/>'
      }
      const result = await captcha(5)
      qrCode.innerHTML = ''
      this.qrRes = result.data
      new QRCode(this.$refs['qr-code'], {
        text: this.qrRes,
        width: 258,
        height: 258,
        colorDark: '#333333', // 二维码颜色
        colorLight: '#ffffff', // 二维码背景色
        logoSrc: '',
        correctLevel: QRCode.CorrectLevel.L // 容错率，L/M/H
      })
      this.isFail = false
      this.handleQrCodeLogin()
    },
    handleQrCodeLogin() {
      this.clearQrTimer()
      this.qrTimer = setInterval(() => {
        notice({ qr_code: this.qrRes })
          .then(res => {
            if (res.data.authorization) {
              this.clearQrTimer()
              this.$store.commit('user/SET_TOKEN', res.data.authorization)
              setToken(res.data.authorization, res.data.cookie)
              setTimeout(() => {
                location.reload()
              }, 500)
            }
          })
      }, 2000)
    },
    clearQrTimer() {
      clearInterval(this.qrTimer)
      this.qrTimer = null
    },
    handleRefresh() {
      this.bindQrCode()
    },
    handleSendCaptcha() {
      if (this.time !== 0) {
        if (!this.captchaForm.phone) {
          Message({
            type: 'warning',
            message: '手机号码不能为空'
          })
          return false
        }
        this.time = 0
        captcha(1, this.captchaForm.phone).then(() => {
          setTimeout(() => {
            this.timer()
          })
        }).catch(() => {
          this.time = null
        })
      }
    },
    timer() {
      this.time = 60
      this.timeInterval = setInterval(() => {
        if (this.time > 0) {
          this.time -= 1
        } else {
          this.time = null
          clearInterval(this.timeInterval)
        }
      }, 1000)
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          let params
          if (this.loginType === 'account') {
            params = { ...this.loginForm }
          } else {
            params = {
              username: this.captchaForm.phone,
              password: this.captchaForm.captcha,
              mode: 'sms'
            }
          }
          this.$store.dispatch('user/login', params)
            .then(() => {
              location.reload()
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100%;
  width: 100%;
  background-image: url('https://media10.pysfeicui.com/login_background1.jpg');
  overflow: hidden;
}

.login-box {
  display: flex;
  height: 450px;
  background: #fff;
}
@media (max-width: 600px) {
  .login-box-l {
    display: none;
  }
  .login-box-r {
    width: 80%;
    justify-content: center;
  }
  .login-box {
    justify-content: center;
  }
}
@media (min-width: 600px) {
  .login-box-l {
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 374px;
    color: #fff;
    background-image: url('https://media10.pysfeicui.com/login_background2.jpg');

    .mask {
      position: absolute;
      top: 0;
      bottom: 0;
      right: 0;
      left: 0;
      background-color: #000;
      opacity: 0.5;
    }
    .logo {
      z-index: 1;
      width: 110px;
      height: 86px;
    }
    .title {
      z-index: 1;
      font-size: 40px;
      line-height: 40px;
      padding: 34px 0 25px;
    }
    .sub {
      z-index: 1;
      font-size: 18px;
      line-height: 18px;
      letter-spacing: 4px;
    }
  }
  .login-box-r {
    width: 474px;
  }
}

.login-box-r {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  padding: 56px 0;
  background-color: #fff;

  .qr {
    cursor: pointer;
  }
  .trigger {
    position: absolute;
    top: 5px;
    right: 5px;
    display: flex;
    align-items: center;
    cursor: pointer;

    .trigger-l {
      color: #409EFF;
      font-size: 14px;
      margin-right: 10px;
    }
    .trigger-r {
      width: 35px;
      height: 35px;
    }
  }
  .header {
    display: flex;
    width: 356px;
    font-size: 20px;
    line-height: 20px;
    color: #444;
    border-bottom: 1px solid #409EFF;
    padding-bottom: 20px;
    .header-item {
      flex: 1 0 1%;
      text-align: center;
      cursor: pointer;
    }
    .active {
      color: #409EFF;
      font-weight: bold;
    }
  }
  .header-qr {
    color: #409EFF;
    font-size: 20px;
    line-height: 20px;
    font-weight: bold;
  }
  .login-form {
    width: 336px;
    padding: 34px 0 40px;
  }
  .verify-text {
    position: absolute;
    right: 0;
    top: 0;
    z-index: 10;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 100%;
    .line {
      position: absolute;
      left: 0;
      height: 15px;
      border-left: 1px solid #E4E7ED
    }
  }
  .footer {
    font-size: 14px;
    color: #444;

    a {
      color: #409EFF;
      cursor: pointer;
    }
  }
}
</style>
